import { NextApiRequest, NextApiResponse } from "next";

import {
  addAppUsers,
  checkAdminAuth,
  getCurrentUserRole,
  upsertAppUserRecords,
} from "@/services";

async function appendAppUsers(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  const withAdminAuth = await checkAdminAuth(req, res);
  if (!withAdminAuth) return;

  const appId = req.body.appid as string;
  const userId = req.body.userid as string;
  const upsertResult = await upsertAppUserRecords(
    Number(appId),
    [Number(userId)],
    1
  );
  res.status(upsertResult.success ? 200 : 400).json(upsertResult);
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  if (req.method === "POST") {
    appendAppUsers(req, res);
  } else {
    res.status(405).json({
      success: false,
      data: {},
      message: "Method not allowed",
    });
  }
}
